/**
 * 通用抽屉组件
 * 支持从右侧滑入滑出，带遮罩和关闭交互
 */

import React, { useEffect, useCallback } from 'react';

export interface DrawerProps {
  visible: boolean;
  title?: string;
  width?: number | string;
  onClose: () => void;
  children: React.ReactNode;
  closable?: boolean;
  maskClosable?: boolean;
  className?: string;
  style?: React.CSSProperties;
}

const Drawer: React.FC<DrawerProps> = ({
  visible,
  title,
  width = 450,
  onClose,
  children,
  closable = true,
  maskClosable = true,
  className = '',
  style = {},
}) => {
  // ESC键关闭
  useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key === 'Escape' && visible) {
        onClose();
      }
    };

    if (visible) {
      document.addEventListener('keydown', handleKeyDown);
      return () => document.removeEventListener('keydown', handleKeyDown);
    }
  }, [visible, onClose]);

  // 防止body滚动
  useEffect(() => {
    if (visible) {
      document.body.style.overflow = 'hidden';
      return () => {
        document.body.style.overflow = '';
      };
    }
  }, [visible]);

  // 遮罩点击关闭
  const handleMaskClick = useCallback(
    (e: React.MouseEvent) => {
      if (maskClosable && e.target === e.currentTarget) {
        onClose();
      }
    },
    [maskClosable, onClose]
  );

  if (!visible) return null;

  const drawerWidth = typeof width === 'number' ? `${width}px` : width;

  return (
    <div
      className={`drawer-container ${className}`}
      style={{
        position: 'fixed',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        zIndex: 1000,
        ...style,
      }}
    >
      {/* 遮罩层 */}
      <div
        className='drawer-mask'
        onClick={handleMaskClick}
        style={{
          position: 'absolute',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          backgroundColor: 'rgba(0, 0, 0, 0.45)',
          animation: visible ? 'fadeIn 0.3s ease-out' : 'fadeOut 0.3s ease-out',
        }}
      />

      {/* 抽屉主体 */}
      <div
        className='drawer-content'
        style={{
          position: 'absolute',
          top: 0,
          right: 0,
          bottom: 0,
          width: drawerWidth,
          backgroundColor: '#fff',
          boxShadow: '-2px 0 8px rgba(0, 0, 0, 0.15)',
          display: 'flex',
          flexDirection: 'column',
          animation: visible
            ? 'slideInRight 0.3s ease-out'
            : 'slideOutRight 0.3s ease-out',
        }}
      >
        {/* 头部 */}
        {(title || closable) && (
          <div
            className='drawer-header'
            style={{
              padding: '16px 24px',
              borderBottom: '1px solid #f0f0f0',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'space-between',
              flexShrink: 0,
              minHeight: '60px',
            }}
          >
            {title && (
              <h3
                style={{
                  margin: 0,
                  fontSize: '16px',
                  fontWeight: 600,
                  color: '#262626',
                  lineHeight: '24px',
                }}
              >
                {title}
              </h3>
            )}

            {closable && (
              <button
                onClick={onClose}
                className='drawer-close-btn'
                style={{
                  background: 'none',
                  border: 'none',
                  fontSize: '16px',
                  cursor: 'pointer',
                  color: '#8c8c8c',
                  width: '32px',
                  height: '32px',
                  borderRadius: '6px',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  transition: 'all 0.2s ease',
                }}
                onMouseEnter={e => {
                  e.currentTarget.style.backgroundColor = '#f5f5f5';
                  e.currentTarget.style.color = '#262626';
                }}
                onMouseLeave={e => {
                  e.currentTarget.style.backgroundColor = 'transparent';
                  e.currentTarget.style.color = '#8c8c8c';
                }}
              >
                ✕
              </button>
            )}
          </div>
        )}

        {/* 内容区域 */}
        <div
          className='drawer-body'
          style={{
            flex: 1,
            overflow: 'auto',
            padding: '24px',
          }}
        >
          {children}
        </div>
      </div>

      {/* CSS动画 */}
      <style>{`
        @keyframes fadeIn {
          from { opacity: 0; }
          to { opacity: 1; }
        }
        
        @keyframes fadeOut {
          from { opacity: 1; }
          to { opacity: 0; }
        }
        
        @keyframes slideInRight {
          from { 
            transform: translateX(100%);
            opacity: 0;
          }
          to { 
            transform: translateX(0);
            opacity: 1;
          }
        }
        
        @keyframes slideOutRight {
          from { 
            transform: translateX(0);
            opacity: 1;
          }
          to { 
            transform: translateX(100%);
            opacity: 0;
          }
        }
        
        .drawer-close-btn:hover {
          background-color: #f5f5f5 !important;
          color: #262626 !important;
        }
        
        .drawer-close-btn:active {
          background-color: #e6f7ff !important;
          color: #1890ff !important;
        }
      `}</style>
    </div>
  );
};

export default Drawer;
